import 'package:flutter/material.dart';
import '../../package/color/color_constant.dart';
import '../../package/layout/NotContent.dart';
import '../../package/nav/AppBarSearch.dart';


import 'package:shared_preferences/shared_preferences.dart';

import '../package_model_comm.dart';



/*
 * 2019.12.31
 * DingHL
 * 信息搜索历史记录页面
 */
//信息搜索历史记录页面
class InfoSearch extends StatefulWidget {
  String hinText;//搜索框提示文本
  List<BaseModel> listData;//接口返回的搜索列表
  ValueChanged<String> searchText;//搜索的关键字

  InfoSearch({
    Key  key,
    this.hinText:"输入搜索的内容",
    this.listData,
    this.searchText,
  }): super(key:key);


  @override
  _InfoSearchState createState() => _InfoSearchState();
}

class _InfoSearchState extends State<InfoSearch> {

  List<String> historyList = List();//显示的历史记录数组
  String historyString = '';//存储的记录字符串
  int showHistory;//搜索记录是否显示（1、显示搜索记录 2、显示搜索结果或者无搜索结果3、用户正在搜索不显示 ）
  bool isLeftIcon;//是否显示左侧图标

  List<BaseModel> listData = [];//数据源
  String searchText = "";//搜索的关键字

  //搜索框控制器
  TextEditingController searchTextController = TextEditingController();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    setState(() {
      showHistory = 1;//初始化时显示历史记录
    });
    //如果接口查出来的列表不为空
    if (widget.listData.isNotEmpty) {
      listData = widget.listData;//查询出来的列表值
    }

  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }



  bool _isDisplaySubmitButton = false;
  //设置返回按钮监听事件
  Future<bool> _onWillPop() {
    setState(() {
      _isDisplaySubmitButton = true; //监听返回按钮监听事件
    });
    Navigator.of(context).pop();
//    Navigator.push(context, new MaterialPageRoute(builder: (context) => null));//跳转页面
  }
  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop:  _onWillPop,
      child: Scaffold(
          appBar:AppBarSearch(
              vertical: 11,//设置提示文本居中，越大往上移，越小往下移
              hinText: widget.hinText,//提示字体
              statusBarColor:themeColor,//搜索导航颜色
              leftIcon: "images/package/search.png",//左侧图标
              isLeftIcon: isLeftIcon == false?false:true,//是否显示左侧图标
              isShowQuitButton: true,//是否显示取消按钮
              fontColor:Colors.black87,//输入的字体颜色
              rightIconColor:Colors.grey[400],//右侧图标颜色
              leftIconSize: 15,
              rightIconSize: 20,
              fontSize: 14,
              controller: searchTextController,
              onTap: (){
                setState(() {
                  isLeftIcon = false;
                });
              },
              //输入改变时
              onChangde: (value){
                setState(() {
                  print(value);
//                  searchText = value;
                });
              },
              //键盘提交完成
              onSubmit: (value){
                saveHistoryInfo(value);//存储输入的值
                searchText = value;
                setState(() {
                  showHistory = 2;//显示搜索结果或者无搜索结果
                });
                widget.searchText(value);//搜索的关键字回调

              },
              //右侧图标×点击事件
              onRight: (v){
                print("点击了清除");
//                setState(() {
//
//                });
                setState(() {
                  showHistory = 1;//显示搜索列表历史记录
                });

              },
              //取消点击事件
              onQuitTop:(){
                Navigator.of(context).pop();
              }
          ),
          body:
          showHistory == 1?
          FutureBuilder(
          future: getList(context),
          builder: (context, snapshot) {
            if(snapshot.hasData) {
              return Stack(
                children: <Widget>[
                  SingleChildScrollView(
                    child: Container(
                      child: Column(
                        children: <Widget>[
                          Container(
                            child: Column(
                              children: _buildGridTileList(historyList),
                            ),
                          ),
                          historyList.length>0?Container(
                              margin: EdgeInsets.only(top: 10,bottom: 10),
                              height: 44,
                              child: InkWell(
                                onTap: (){
                                  print('清除历史记录');
                                  removeHistory();
                                },
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: <Widget>[
                                    Container(
                                      child: ImageIcon(
                                        AssetImage("images/package/del.png"),
                                        color: Color(0xFF999999),
                                        size: 16,
                                      ),
                                    ),
//                                    Container(
//                                      child: Icon(Icons.delete_forever,color: Color(0xFF999999),size: 20,),
//                                    ),
                                    Container(
                                      margin: EdgeInsets.only(left: 7),
                                      child: Text('清除历史记录',style: TextStyle(color: Color(0xFF999999),fontSize: 14),),
                                    )
                                  ],
                                ),
                              )
                          ):SizedBox(width:375,)
                        ],
                      ),
                    ),
                  ),
                ],

              );
            }else {
              return Text('正在加载');
            }
          },
        ):
          showHistory == 2?
          Container(
            child: listData.length<=0?
            NotContent():
            ListView.builder(
              itemCount: listData.length,
              itemBuilder: (context, index){
                return InkWell(
                  onTap: (){
                  },
                  child: Container(
                    decoration: BoxDecoration(
                        border: Border(
                            bottom: BorderSide(color: Color(0xFFF5F5F5),width: 2)
                        )
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        Container(
                          padding: EdgeInsets.only(left: 5),
                          child: getWidgetByString(listData[index].name),
                        ),
//                   //未设置高亮显示行
//                    Container(
//                      padding: EdgeInsets.fromLTRB(10, 15, 10, 15),
////                      height: 47,
////                      color: Colors.red,
//                      child: Text(
//                        data[index],
//                        style: TextStyle(fontSize: 16),
//                      ),
//                    ),
//                    //删除按钮
//                      InkWell(
//                        child: Container(
//                          margin: EdgeInsets.only(right: 20),
//                          child:Icon(Icons.clear,size: 18,),
//                        ),
//                        //删除
//                        onTap: (){},
//                      ),
                      ],
                    ),
                  ),
                );
              },
            ),
          ):Container(),
      ),
    );
  }


  ///记录列表
  List<Widget> _buildGridTileList(List list) {
    return new List.generate(
        list.length,
            (int index) => new Container(
          child: _listItem(list[index]),
        )
    );
  }

  Widget _listItem(String title){
    return Container(
      decoration: BoxDecoration(
          border: Border(
              bottom: BorderSide(color: Color(0xFFF5F5F5),width: 1)
          )
      ),
      child: InkWell(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Container(
              padding: EdgeInsets.only(left: 15),
              child: Text(title, style: TextStyle(color: Color(0xFF333333),fontSize: 14),),
            ),
            Container(
              child: IconButton(
                  icon: Icon(
                    Icons.clear,
                    color:Color(0xFF999999),
                    size: 18,
                  ),
                  onPressed: (){
                    ///删除单条历史记录
                    removeOneHistory(title);
                  }),
            ),
          ],
        ),
        onTap: (){
          searchTextController.text = title;//将点击的历史记录赋值给搜索框
          setState(() {
            searchText = title;//给搜索关键字赋值
            showHistory = 2;//显示搜索结果或者无搜索结果
          });
        },
      )
//      child: ListTile(
//        title:Text(title, style: TextStyle(color: Color(0xFF333333),fontSize: 14),),
//        trailing: IconButton(
//            icon: Icon(
//              Icons.clear,
//              color:Color(0xFF999999),
//              size: 18,
//            ),
//            onPressed: (){
//              ///删除单条历史记录
//              removeOneHistory(title);
//            }),
//        onTap: (){
//          searchTextController.text = title;//将点击的历史记录赋值给搜索框
//          setState(() {
//            searchText = title;//给搜索关键字赋值
//            showHistory = 2;//显示搜索结果或者无搜索结果
//          });
//
//        },
//      ),
    );
  }

  ///保存
  saveHistoryInfo(searchStr) async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    historyString = prefs.getString('historyInfo');//存储

//    //判断当为空 为null时不操作  tempList操作的数组
    List<String> tempList = historyString == null || historyString == ''?[]:historyString.split(',');//强转成List


    //去除历史记录重复
    bool isDul = false;
    tempList.forEach((title){
      if(title == searchStr){
        isDul = true;
      }
    });

    if(isDul) {
      return;
    }

    tempList.insert(0, searchStr);//搜索内容插入到第一个
    historyList.insert(0, searchStr);

    //当搜索记录超过10条是移除最后一条
    if(historyList.length>10){
      tempList.removeLast();
      historyList.removeLast();
    }

    historyString = getStringsForList(tempList);//数组转成字符串

    prefs.setString('historyInfo', historyString);//存储字符串


  }

  ///获取
  getHistoryInfo() async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    historyString = prefs.getString('historyInfo');
    historyList = [];

    if(historyString==null || historyString == ''){
      setState(() {
        historyList = [];
      });
    }else{
      setState((){});
      List<String> tempList = historyString.split(',');//字符串以逗号分隔成数组
      tempList.forEach((title){
        historyList.add(title);
      });
    }


  }

  ///移除所有
  removeHistory() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.remove('historyInfo');
    historyList = [];
    print('清空历史记录');

    await getHistoryInfo();
  }

  ///移除单项
  removeOneHistory(String value) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    historyString = prefs.getString('historyInfo');
    List<String> tempList = historyString.split(',');
    int tempIndex=0;
    int deleteIndex=0;
    tempList.forEach((title){
      if(title == value){
        deleteIndex = tempIndex;
      }

      tempIndex++;
    });

    tempList.removeAt(deleteIndex);
    historyString = getStringsForList(tempList);
    prefs.setString('historyInfo', historyString);

    await getHistoryInfo();
  }

  //搜索历史记录列表
  Future<String> getList(BuildContext context) async{
    await getHistoryInfo();

    return 'end';
  }

  ///数组转字符串
  getStringsForList(List data){
    String str = '';
    if(data.length>0){
      for(String item in data){
        String string = '';
        if(str.length>0){
          string = ',';
        }
        str = str + string + item;
      }

    }

    return str;
  }

  //根据String实现搜索变色  返回控件
  Widget getWidgetByString(String str) {
    Widget w = Container(
//      width: MediaQuery.of(context).size.width-50,
      height: 47,
      child: Text('', overflow: TextOverflow.ellipsis, maxLines: 1,),
    );
    String a = '';
    String b = '';
    String se = searchText.toUpperCase();//输入的字母转大小
    String s= str.toUpperCase();//显示的字母转大小

//    print('str:${s}');
//    print('se:${se}');
    //判断是否包含输入的值
    if (str.toUpperCase().contains(se)) {
      int j = s.indexOf(se);
      print('j：$j');
      print('str：$s');
      //表示第一位的
      if (j == 0) {
        print('开始位置$j');
        w = Container(
            alignment: Alignment.centerLeft,
            margin: EdgeInsets.only(left: 10),
//            width: MediaQuery.of(context).size.width-60,
            height: 47,
            child:
            RichText(
                text: TextSpan(
                    text: se,
                    style: TextStyle(
                      fontSize: 14,
                      color: Color(0xff4884f1),
                    ),
                    children: <TextSpan>[
                      TextSpan(text:  s.substring(se.length, s.length),
                          style: TextStyle(
                              fontSize: 14.0,
                              color: Color(0xFF333333)))
                    ]))
        );
      } else if (j > 0 && j < s.length) {
        print('中间位置$j');
        a = s.substring(0, s.indexOf(se));
        b = s.substring(s.indexOf(se) + se.length, s.length);
        print('a：$a');
        print('b：$b');
        w = Container(
            alignment: Alignment.centerLeft,
            margin: EdgeInsets.only(left: 10),
//            width: MediaQuery.of(context).size.width-60,
            height: 47,
            child: RichText(
                text: TextSpan(
                    text: a,
                    style: TextStyle(
                      fontSize: 14,
                      color: Color(0xFF333333),
                    ),
                    children: <TextSpan>[
                      TextSpan(text: se,
                        style: TextStyle(
                            fontSize: 14.0,
                            color: Color(0xff4884f1)),),
                      TextSpan(text: b,
                        style: TextStyle(
                            fontSize: 14.0,
                            color: Color(0xFF333333)),),
                    ]))
        )
        ;
      } else if (j == s.length) {
        print('末尾位置$j');
        a = s.substring(0, s.length - 1);
        w = Container(
            alignment: Alignment.centerLeft,
            margin: EdgeInsets.only(left: 10),
//            width: MediaQuery.of(context).size.width-60,
            height: 47,
            child: RichText(
              text: TextSpan(
                  text: a,
                  style: TextStyle(
                    fontSize: 14,
                    color: Color(0xFF333333),
                  ),
                  children: <TextSpan>[
                    TextSpan(text: se,
                      style: TextStyle(
                          fontSize: 14.0,
                          color: Color(0xff4884f1)),),
                  ]),)
        )
        ;
      }
    } else {
      print('没有查到该数据');
    }
    return w;
  }

}
